"""
管理员访问码验证对话框
用于在管理员登录前进行第一层验证
"""

import tkinter as tk
from tkinter import ttk, messagebox
import customtkinter
from core.services.admin_service import AdminService
from core.utils.logger import info, warning, error
from ui.styles.theme import Theme


class AdminAccessDialog:
    """管理员访问码验证对话框"""
    
    def __init__(self, parent):
        self.parent = parent
        self.admin_service = AdminService()
        self.result = False
        self.dialog = None
    
    def show(self) -> bool:
        """
        显示访问码验证对话框
        
        Returns:
            bool: 验证是否成功
        """
        # 创建对话框
        self.dialog = customtkinter.CTkToplevel(self.parent)
        self.dialog.title("Admin Access Verification")
        self.dialog.geometry("450x320")
        self.dialog.resizable(False, False)
        
        # 设置对话框为模态
        self.dialog.transient(self.parent)
        self.dialog.grab_set()
        
        # 居中显示
        self._center_dialog()
        
        # 创建界面
        self._create_widgets()
        
        # 等待对话框关闭
        self.dialog.wait_window()
        
        return self.result
    
    def _center_dialog(self):
        """将对话框居中显示"""
        self.dialog.update_idletasks()
        width = 450
        height = 320
        x = (self.dialog.winfo_screenwidth() // 2) - (width // 2)
        y = (self.dialog.winfo_screenheight() // 2) - (height // 2)
        self.dialog.geometry(f"{width}x{height}+{x}+{y}")
    
    def _create_widgets(self):
        """创建界面组件"""
        # 主容器
        main_frame = customtkinter.CTkFrame(self.dialog, fg_color="transparent")
        main_frame.pack(fill="both", expand=True, padx=30, pady=30)
        
        # 标题
        title_label = customtkinter.CTkLabel(
            main_frame,
            text="🔐 Admin Access Verification",
            font=("Arial", 18, "bold"),
            text_color=Theme.get_color('fg_primary')
        )
        title_label.pack(pady=(0, 10))
        
        # 说明文本
        info_label = customtkinter.CTkLabel(
            main_frame,
            text="Please enter the admin access code to continue",
            font=("Arial", 11),
            text_color=Theme.get_color('fg_secondary'),
            wraplength=350,
            justify="center"
        )
        info_label.pack(pady=(0, 25))
        
        # 访问码输入框架
        input_frame = customtkinter.CTkFrame(main_frame, fg_color="transparent")
        input_frame.pack(fill="x", pady=(0, 20))
        
        access_code_label = customtkinter.CTkLabel(
            input_frame,
            text="Access Code:",
            font=("Arial", 12),
            text_color=Theme.get_color('fg_primary')
        )
        access_code_label.pack(anchor='w', pady=(0, 8))
        
        # 访问码输入框
        self.access_code_var = tk.StringVar()
        self.access_code_entry = customtkinter.CTkEntry(
            input_frame,
            textvariable=self.access_code_var,
            show="•",
            font=("Arial", 13),
            width=350,
            height=38,
            corner_radius=8
        )
        self.access_code_entry.pack(fill='x')
        self.access_code_entry.focus()
        
        # 绑定回车键
        self.access_code_entry.bind('<Return>', lambda e: self._verify_access_code())
        
        # 状态标签
        self.status_label = customtkinter.CTkLabel(
            main_frame,
            text="",
            font=("Arial", 10),
            text_color=Theme.get_color('error'),
            wraplength=350
        )
        self.status_label.pack(pady=(0, 15))
        
        # 按钮框架
        button_frame = customtkinter.CTkFrame(main_frame, fg_color="transparent")
        button_frame.pack(fill="x", pady=(0, 10))
        
        # 取消按钮
        cancel_btn = customtkinter.CTkButton(
            button_frame,
            text="Cancel",
            command=self._cancel,
            width=120,
            height=35,
            fg_color=Theme.get_color('fg_secondary'),
            hover_color=Theme.get_color('fg_tertiary'),
            corner_radius=8
        )
        cancel_btn.pack(side="right", padx=(8, 0))
        
        # 验证按钮
        verify_btn = customtkinter.CTkButton(
            button_frame,
            text="Verify",
            command=self._verify_access_code,
            width=120,
            height=35,
            fg_color=Theme.get_color('accent'),
            hover_color=Theme.get_color('accent_hover'),
            corner_radius=8
        )
        verify_btn.pack(side="right")
        
        # 底部提示
        hint_label = customtkinter.CTkLabel(
            main_frame,
            text="💡 Tip: Access code is used to verify admin identity",
            font=("Arial", 9),
            text_color=Theme.get_color('fg_tertiary'),
            wraplength=350
        )
        hint_label.pack(pady=(15, 0))
    
    def _verify_access_code(self):
        """验证访问码"""
        access_code = self.access_code_var.get().strip()
        
        if not access_code:
            self._show_error("Please enter access code")
            return
        
        try:
            # 验证访问码
            success, error_msg = self.admin_service.verify_access_code(access_code)
            
            if success:
                info("Admin access code verified successfully")
                self.result = True
                self.dialog.destroy()
            else:
                self._show_error(error_msg)
                # 清空输入框
                self.access_code_var.set("")
                self.access_code_entry.focus()
                
        except Exception as e:
            error(f"Exception while verifying access code: {e}")
            self._show_error("Error occurred during verification, please try again")
    
    def _show_error(self, message: str):
        """显示错误消息"""
        self.status_label.configure(text=message, text_color=Theme.get_color('error'))
        self.dialog.after(3000, lambda: self.status_label.configure(text=""))  # 3秒后清除消息
    
    def _cancel(self):
        """取消验证"""
        self.result = False
        self.dialog.destroy()
    
    def _on_closing(self):
        """对话框关闭时的处理"""
        self.result = False
        self.dialog.destroy()


